package com.nowcoder.community.service;

import com.nowcoder.community.dao.CommonRedisDao;
import com.nowcoder.community.dao.EntityLikeDao;
import com.nowcoder.community.event.LikeEvent;
import com.nowcoder.community.event.producer.DefaultEventProducer;
import com.nowcoder.community.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikeService {

    @Autowired
    EntityLikeDao entityLikeDao;

    @Autowired
    DefaultEventProducer defaultEventProducer;

    @Autowired
    CommonRedisDao commonRedisDao;

    private void sendLikeEvent(int userId, int userIdOfEntity, int entityType, int entityId) {
        defaultEventProducer.sendLikeEvent((LikeEvent) new LikeEvent()
                .setLikeUserId(userId)
                .setUserIdOfEntity(userIdOfEntity)
                .setEntityId(entityId)
                .setEntityType(entityType)
                .setCreateTime(System.currentTimeMillis()));
    }

    /**
     * 为用户某实体点赞
     * @param userId 点赞的用户
     * @param userIdOfEntity 被点赞实体所属用户
     * @param entityType 被点赞的实体类型
     * @param entityId 被点赞的实体id
     */
    public void like(int userId, int userIdOfEntity, int entityType, int entityId) {
        entityLikeDao.like(entityType, entityId, userId, userIdOfEntity);
        if (!commonRedisDao.hasLikedHistory(userId, entityId)) {
            sendLikeEvent(userId, userIdOfEntity, entityType, entityId);
            commonRedisDao.setUserLikeHistory(userId, entityId);
        }
    }


    public void unlike(int userId, int userIdOfEntity, int entityType, int entityId) {
        entityLikeDao.unlike(entityType, entityId, userId, userIdOfEntity);
    }

    public long countCommentLike(int id) {
        return entityLikeDao.selectEntityLikeCount(Constants.ENTITY_TYPE_COMMENT, id);
    }

    public long countPostLike(Integer id) {
        return entityLikeDao.selectEntityLikeCount(Constants.ENTITY_TYPE_POST, id);
    }

    public int getPostLikeStatus(int userId, int postId) {
        return entityLikeDao.getLikeStatus(userId, Constants.ENTITY_TYPE_POST, postId);
    }

    public int getCommentLikeStatus(int userId, int commentId) {
        return entityLikeDao.getLikeStatus(userId, Constants.ENTITY_TYPE_COMMENT, commentId);
    }

    public long countUserLike(int userId) {
        return entityLikeDao.selectUserLikeCount(userId);
    }
}
